package com.vae.base.exception.handle;

import com.vae.base.enums.SystemExceptionEnum;
import com.vae.base.exception.SystemException;
import com.vae.base.exception.response.SystemErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
/**
 * @author: vae
 * 功能: 全局异常处理器
 * 时间: 2024-04-04 16:18
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public SystemErrorResponse customException(SystemException e) {
        log.error("【系统异常】{}",e.getErrMessage(),e);
        return new SystemErrorResponse(e.getErrMessage());

    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public SystemErrorResponse exception(Exception e) {
        log.error("【系统异常】{}",e.getMessage(),e);
        if(e.getMessage().equals("不允许访问")) {
            return new SystemErrorResponse("您没有权限访问");
        }
        return new SystemErrorResponse(SystemExceptionEnum.UNKOWN_ERROR.getErrMessage());
    }
    //字段检验出错时，会返回给前端具体的message.这个message是你在实体类字段的@Size、@Min、@NotEmpty等校验注解的message属性值
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public SystemErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<String> msgList = new ArrayList<>();
        //将错误信息放在msgList
        bindingResult.getFieldErrors().stream().forEach(item->msgList.add(item.getDefaultMessage()));
        //拼接错误信息
        String msg = StringUtils.join(msgList, ",");
        log.error("【系统异常】{}",msg);
        return new SystemErrorResponse(msg);
    }
}
